<template>
  <div>
    <div class="chat-wrapper">
      <el-page-header
          @back="goBack"
      >
      </el-page-header>
      <div class="content-area" ref="contentArea">
        <div
            v-for="(msgItem, index) in msgList"
            :key="index"
            class="msg-item"
        >
          <div
              :style="{
              float: msgItem.type === 'other'?'left':'right'
            }"
          >
            <div
                :style="{
                  float: msgItem.type === 'other'?'left':'right',
                  margin: '10px',
                  textAlign: 'center'
                }"
            >
              <el-avatar :size="40" :src="msgItem.avatar" style="display: block;"></el-avatar>
              <span style="font-size: 12px;">{{ msgItem.userName }}</span>
            </div>
            <el-card
                class="box-card"
                style="margin: 0 10px;"
                :style="{
                  float: msgItem.type === 'other'?'left':'right'
                }"
            >
              <span v-if="msgItem.msg.type==='text'">{{ msgItem.msg.content }}</span>
              <el-image v-else :src="msgItem.msg.content"></el-image>
            </el-card>
          </div>
        </div>
      </div>
      <div class="tool-bar">
        <el-row style="text-align: center;">
          <el-col :span="2">
            <div class="select-img" style="width: 100%;text-align: center;">
              <i class="el-icon-picture-outline"></i>
              <input
                  @change="sendImg"
                  type="file"
                  ref="selectImg"
                  style="position: absolute;z-index: 10;top: 0;left: 0;opacity: 0;"
              >
            </div>
          </el-col>
          <el-col :span="20">
            <el-input v-model="msgText" @keypress.enter.native="sendText"></el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="text" icon="el-icon-s-promotion" @click="sendText"></el-button>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>

import defaultConfig from "@/config/config.default";

async function cutImageBase64(files, width, quality) { // 这个函数是万老的一个定式
  return new Promise((resolve) => {
    const file = files[0]; // 获取文件
    let URL = window.URL || window.webkitURL; // 获取文件地址
    const blog = URL.createObjectURL(file); // 转成真实的blog地址
    let base64;
    const img = new Image();
    img.src = blog;
    img.onload = function () {
      const that = this;
      let w = that.width;
      let h = that.height;
      let scale = w / h;
      w = width || w;
      h = w / scale;
      const canvas = document.createElement('canvas'); // 获取canvas
      const canCon = canvas.getContext('2d'); // 获取canvas的绘制上下文
      canvas.width = w;
      canvas.height = h;
      canCon.drawImage(that, 0, 0, w, h); // 绘制
      base64 = canvas.toDataURL('image/jpeg', quality || 0.8); // 转格式
      resolve(base64); // 返回出去
    }
  })
}

export default {
  name: "Chathome",
  data() {
    return {
      socket: null,
      msgText: '',
      message: {
        userName: '',
        avatar: '',
        msg: {
          type: '',
          content: ''
        }
      },
      userData: JSON.parse(sessionStorage.getItem('userData')),
      msgList: []
    }
  },
  watch: {
    userData: {
      handler() {
        this.message.userName = this.userData.userName;
        this.message.avatar = this.userData.avatar;
      },
      immediate: true
    }
  },
  mounted() { // 当用户加载的时候
    this.socket = new WebSocket(`${defaultConfig.wssApiUrl}`); // 连接
    let vm = this;
    this.socket.addEventListener('open', function () { // 监听事件的时候注意this指向
      vm.$message.success('加入聊天室');
    })
    this.socket.addEventListener('message', function (event) {
      vm.msgList.push({
        ...JSON.parse(event.data),
        type: 'other' // 这是标记别人发给我的信息
      })
      vm.$nextTick(function (){
        vm.$refs.contentArea.scrollTop = vm.$refs.contentArea.scrollHeight;
      })
    })
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    sendImg() {
      console.log(this.$refs.selectImg.files);
      cutImageBase64(this.$refs.selectImg.files, 400, 0.9).then(rs => {
        this.message.msg.type = 'img';
        this.message.msg.content = rs;
        this.socket.send(JSON.stringify(
            this.message
        )); // 向远程服务器发送基本数据
        this.msgList.push({
          ...JSON.parse(JSON.stringify(this.message)), // 取一个副本，因为每次发信息都不一样
          type: 'me' // 这是标记我发给别人的信息
        });
        this.message.msg.type = ''; // 发送完之后清空
        this.message.msg.content = ''; // 发送完之后清空
        this.$nextTick(function (){
          this.$refs.contentArea.scrollTop = this.$refs.contentArea.scrollHeight;
        })
      })
    },
    sendText() {
      if (this.msgText) {
        this.message.msg.type = 'text';
        this.message.msg.content = this.msgText;
        this.socket.send(JSON.stringify(
            this.message
        )); // 向远程服务器发送基本数据
        this.msgText = ''; // 发送完之后就清空
        this.msgList.push({
          ...JSON.parse(JSON.stringify(this.message)), // 取一个副本，因为每次发信息都不一样
          type: 'me' // 这是标记我发给别人的信息
        });
        this.message.msg.type = ''; // 发送完之后清空
        this.message.msg.content = ''; // 发送完之后清空
        this.$nextTick(function (){
          this.$refs.contentArea.scrollTop = this.$refs.contentArea.scrollHeight;
        })
      }
    }
  }
}
</script>

<style>
body {
  margin: 0;
  //overflow: hidden; /*设置了一个overflow:hidden，所以比万老的多一行*/
}

.chat-wrapper {
  position: relative;
  width: 100vw;
  height: 100vh;
}

.content-area {
  width: 100vw;
  height: calc(100vh - 64px);
  //background-color: #f30d0d;
  overflow-y: scroll;
}

.select-img {
  position: relative;
  line-height: 40px;
  overflow: hidden;
}

.tool-bar {
  position: absolute;
  box-sizing: border-box;
  bottom: 0;
  left: 0;
  height: 40px;
  width: 100%;
}
.msg-item{
  margin-bottom: 20px;
}
.msg-item::after{
  content: '';
  display: block;
  clear: both;
}
</style>
